<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/*用户访问统计model*/

class AccessNumUser extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = null;


    protected $table = 'access_num_user';

    /**
     * 记录浏览量
     * @param type  类型  1 微信  2 web  3 小程序
     * @return void
     */
    public function addUserNum($type = 1, $user_id)
    {
        $time = time();
        $date = date("Y-m-d", $time);

        $browse = $this->where('date', $date)->where('user_id', $user_id)->first();

        $number = mt_rand(1, 5);
        $type = $type == 1 ? 'wx_num' : ($type == 3 ? 'applet_num' : 'web_num');
        if ($browse) {
            $browse->$type = $browse->$type + $number;
            $browse->total_num = $browse->total_num + $number;
            $browse->save();
        } else {
            $this->date = $date;
            $this->user_id = $user_id;
            $this->$type = 1;
            $this->total_num = 1;
            $this->save();
        }
    }

    /**
     * 用户访问天数
     * @param $start_time 开始时间
     * @param $end_time 结束时间
     */
    public function getUserAccessDay($user_id)
    {
        $res = $this->where('user_id', $user_id)->groupBy('date')->get()->toArray();
        return count($res);
    }
}
